package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOProperties;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleHtmlTasks {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService apArticleService;

    @Autowired
    private MinIOProperties minIOProperties;


    @Async
    public void creatArticleHtml(ApArticle apArticle, String content) {
        try {
            Long articleId = apArticle.getId();

            //获取模板
            Template template = configuration.getTemplate("article.ftl");

            List<Map> mapList = JSON.parseArray(content, Map.class);

            Map dateModel = new HashMap();
            dateModel.put("content", mapList);

            //结合页面
            StringWriter writer = new StringWriter();
            template.process(dateModel, writer);

            //上传minIO中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            minIOService.upload("/article/" + articleId + ".html", inputStream, "text/html");

            String staticUrl = minIOProperties.getEndpoint() + "/" + minIOProperties.getBucketName()+"/article/" + articleId + ".html";

            apArticle.setStaticUrl(staticUrl);
            apArticleService.updateById(apArticle);

        } catch (Exception e) {
            log.error("静态页面生成失败"+apArticle.getId());
        }
    }
}
